package com.vdongchina.thread.base;

/**
 * 第7课:threadLocal线程变量
 * <p>
 * threadLocal以自身为key, 任意对象为value 与线程绑定;可以实现多线程的资源不冲突, 如jdbc的connection
 * <p>
 * ThreadLocal用于保存某个线程共享变量：对于同一个static ThreadLocal，不同线程只能从中get，set，remove自己的变量，而不会影响其他线程的变量。
 */
public class ThreadLocalDemo {

    private static final ThreadLocal<Object> THREAD_LOCAL = new ThreadLocal() {
        @Override
        protected Object initialValue() {
            System.out.println("调用get方法时，当前线程共享变量没有设置，调用initialValue获取默认!");
            return null;
        }
    };


    public static void main(String[] args) {
        new Thread(new MyIntegerTask("IntegerTask1")).start();
        new Thread(new MyIntegerTask("IntegerTask2")).start();
    }


    public static class MyIntegerTask implements Runnable {

        private String name;

        public MyIntegerTask(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                // ThreadLocal.get方法获取线程变量
                if (null == ThreadLocalDemo.THREAD_LOCAL.get()) {
                    // ThreadLocal.et方法设置线程变量
                    ThreadLocalDemo.THREAD_LOCAL.set(0);
                    System.out.println("线程" + name + ": 0");
                } else {
                    int num = (Integer) ThreadLocalDemo.THREAD_LOCAL.get();
                    ThreadLocalDemo.THREAD_LOCAL.set(num + 1);
                    System.out.println("线程" + name + ": " + ThreadLocalDemo.THREAD_LOCAL.get());
                    if (i == 3) {
                        ThreadLocalDemo.THREAD_LOCAL.remove();
                    }
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

